package deptlogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/zeromicro/go-zero/core/logx"
)

type IsExDeptNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
	getDeptListLogic *GetDeptListLogic
}

func NewIsExDeptNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IsExDeptNameLogic {
	return &IsExDeptNameLogic{
		ctx:              ctx,
		svcCtx:           svcCtx,
		Logger:           logx.WithContext(ctx),
		getDeptListLogic: NewGetDeptListLogic(ctx, svcCtx),
	}
}

func (l *IsExDeptNameLogic) IsExDeptName(in *syspb.IsExDeptNameReq) (*syspb.IsExDeptNameResp, error) {
	if in.GetDeptName() == "" {
		return &syspb.IsExDeptNameResp{IsExist: true}, nil
	}

	// 查询条件
	params := &syspb.GetDeptListReq{
		Page: &syspb.PageReq{
			IsCount: true,
		},
		DeptName: in.GetDeptName(),
		ParentId: convertor.ToString(in.GetParentId()),
	}
	if in.GetIsNotId() != 0 {
		params.IsNotId = in.GetIsNotId()
	}

	// 查询
	listResp, err := l.getDeptListLogic.GetDeptList(params)
	if err != nil {
		return nil, err
	}

	// 数据转换
	isExist := true
	if listResp.GetPage().GetTotal() == 0 {
		isExist = false
	}

	return &syspb.IsExDeptNameResp{IsExist: isExist}, nil
}
